package pers.liu.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.liu.entity.Department;
import pers.liu.entity.Employee;
import pers.liu.service.DepartmentService;
import pers.liu.service.EmployeeService;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author LiuGuangShuo
 * @since 2024年11月13日
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DepartmentService departmentService;

    @GetMapping
    public PageInfo<Employee> list(
            @RequestParam(value = "pageSize", defaultValue = "5", required = false) int pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) int pageNum,
            @RequestParam(value = "name", defaultValue = "", required = false) String name,
            @RequestParam(value = "employeeNumber", defaultValue = "", required = false) String employeeNumber,
            @RequestParam(value = "hireDate", defaultValue = "", required = false) String hireDate


    ) {
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<Employee> qw = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            qw.like("name",name);
        }
        if(StringUtils.isNotBlank(employeeNumber)){
            qw.eq("employee_number",employeeNumber);
        }
        if(StringUtils.isNotBlank(hireDate)){
            qw.eq("hire_date",hireDate);
        }
        List<Employee> list = employeeService.list(qw);
        //在list返回之前把list集合中每一个对象的部门信息补全
        list.forEach(emp->{
            Integer departmentId = emp.getDepartmentId();
            Department department = departmentService.getById(departmentId);
            emp.setDepartment(department);
        });
        return new PageInfo<>(list);
    }

    //id查询
    @GetMapping("/{id}")
    public Employee byId(@PathVariable Long id) {
        return employeeService.getById(id);
    }

    //增加
    @PostMapping
    public boolean save(@RequestBody Employee employee) {
        return employeeService.save(employee);
    }

    //修改
    @PutMapping
    public boolean update(@RequestBody Employee employee) {
        return employeeService.updateById(employee);
    }

    //删除
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        return employeeService.removeById(id);
    }
}
